<?php

namespace App\Http\Controllers;

use App\Jobs\SendReminderEmail;
use App\Models\Pages;
use App\Providers\RiakServiceProvider;
use App\Util\RabbitMqTest;
use Facade\FlareClient\Api;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Monolog\Logger;

class TestController extends Controller
{

    private $exchangeName = 'demo';
    private $routeKey = 'hello';
    private $message = 'Hello World!';

    public function __construct()
    {
        $this->middleware(function ($request,$next){
            //echo json_encode($request);
            return $next($request);
        });
    }

    public function test2(Request $request)
    {
        //echo 1;exit;
        $page = Pages::find(1);
        $this->dispatch(new SendReminderEmail($page));
    }

    public function test()
    {

        SendReminderEmail::dispatch(Pages::where());exit;
//        $pages = Pages::query()->where('website_id','=',7)->get()->toArray();
//        //$pages = Pages::with('pack')->limit(2)->get()->toArray();
//        echo json_encode($pages);exit;
    }

    public function consume()
    {

        /**
         * 接收消息
         */
        $exchangeName = 'demo';
        $queueName = 'hello';
        $routeKey = 'hello';
// 建立TCP连接
        $connection = new \AMQPConnection([
            'host' => 'localhost',
            'port' => '5672',
            'vhost' => '/',
            'login' => 'guest',
            'password' => 'guest'
        ]);
        $connection->connect() or die("Cannot connect to the broker!\n");
        $channel = new \AMQPChannel($connection);
        $exchange = new \AMQPExchange($channel);
        $exchange->setName($exchangeName);
        $exchange->setType(AMQP_EX_TYPE_DIRECT);
        echo 'Exchange Status: ' . $exchange->declareExchange() . "\n";
        $queue = new \AMQPQueue($channel);
        $queue->setName($queueName);
        echo 'Message Total: ' . $queue->declareQueue() . "\n";
        echo 'Queue Bind: ' . $queue->bind($exchangeName, $routeKey) . "\n";
        var_dump("Waiting for message...");
// 消费队列消息
        while (TRUE) {
            $queue->consume(function ($envelope, $queue)
            {
                $msg = $envelope->getBody();
                var_dump("Received: " . $msg);
                $queue->ack($envelope->getDeliveryTag()); // 手动发送ACK应答
            });
        }

// 断开连接
        $connection->disconnect();

    }


}
